<template>
	<view class="shop-car">
		<cart-list :list="goodsProducts" @onDeleteClick="handleDeleteClick" @onChooseItem="handleChooseItem"
			@onNumberClick="handleNumberClick" @onCheckClick="handleCheckItem" @onCheckAll="handleCheckAll"
			@onCreateOrderClick="handleCreateOrder"></cart-list>
		<image src="" mode=""></image>
		<bottom-nav :checkedIndex="2" />
	</view>
</template>

<script>
	import {
		getCartList,
		cartRemove,
		cartDecrease,
		cartIncrease
	} from '@/config/api.js'
	export default {
		data() {
			return {
				goodsProducts: [],
			}
		},
		onShow() {
			this.init()
		},
		methods: {
			init() {
				getCartList().then(res => {
					this.goodsProducts = res.data && res.data.map((item, index) => {
						return {
							...item,
							checked: this.goodsProducts?. [index]?.checked || false
						}
					})
				})
			},
			handleCreateOrder(list) {
				//结算
				list = list.map(e=>{
					console.log(e,"商品");
					return e.goods_id
				})
				this.$tool.pageTo('/order/create/create?id='+JSON.stringify(list))
			},
			handleCheckAll(bl) {
				this.goodsProducts = this.goodsProducts.map(e => {
					return {
						...e,
						checked: bl
					}
				})
			},
			handleChooseItem(id) {
				uni.navigateTo({
					url: `/pages/goods/detail/detail?id=${id}`
				})
			},
			handleNumberClick(param) {
				const {
					addOrRemove,
					id,
					gid
				} = param
				const map = {
					"add": cartIncrease,
					"remove": cartDecrease
				}
				map[addOrRemove](id, gid, 1).then(res => {
					this.init()
				})
			},
			handleCheckItem(index) {
				this.goodsProducts = this.goodsProducts.map((item, i) => {
					let checked = item.checked
					if (index === i) checked = !item.checked
					return {
						...item,
						checked
					}
				})
			},
			handleDeleteClick() {
				const delTask = this.goodsProducts
					.filter(goods => goods.checked)
					.map(goods => {
						console.log(goods, "goods")
						return cartRemove(goods.id)
					})
				if (delTask.length === 0) {
					return this.$tool.message('没有选择商品')
				}
				uni.showModal({
					title: `确定删除这${delTask.length}件商品吗？`,
					confirmText: "确定",
					cancelText: "取消",
					confirmColor: "#F13430",
					success: (res) => {
						if (res.confirm) {
							Promise.all(delTask).then(result => {
								this.$tool.message('删除成功')
								this.init()
							}).catch(error => {
								this.$tool.message("删除错误，请联系管理员")
							})
						}
					}
				})

			}
		}
	}
</script>

<style lang="scss" scoped>
	.shop-car {
		width: 750rpx;
		min-height: 100vh;
		display: flex;
		flex-direction: column;
		align-items: center;
		background: #F5F5F5;
	}
</style>
